#include "leecode.h"

#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
      size_t total = nums.size();
      for(size_t i = 0; i < total - 1; i++) {
        for(size_t j = i+1; j < total; j++) {
          vector<int> arr;
          if(nums[i] > nums[j]) {
            arr.push_back(j);
            arr.push_back(i);
          } else {
            arr.push_back(i);
            arr.push_back(j);
          }

          bool exists = false;
          for(size_t x = 0; x < m_vec.size(); x++) {
            if(IsEqual(m_vec[x], arr))
              exists = true;
            Insert(m_vec[x], nums[j]);
          }
          if(!exists)
            m_vec.emplace_back(std::move(arr));
        }
      }
      vector<vector<int>> vec;
      for(int i = 0; i < m_vec.size(); i++) {
        if(m_vec[i].size() == 3) {
          bool bfind = false;
          for(int j = 0; j < vec.size(); j++) {
            if(IsEqual(vec[j], m_vec[i])) {
              bfind = true;
              break;
            }
          }
          if(!bfind)
            vec.push_back(m_vec[i]);
        }

      }
      return std::move(vec);
    }

    bool IsEqual(const vector<int>& v1, const vector<int>& v2) {
      return (v1[0] == v2[0]) && (v1[1] == v2[1]);
    }

    bool Insert(vector<int>& v, int num) {
      switch(v.size()){
      case 0:
        v.push_back(num);
      break;
      case 1:{
        int tmp = v[0];
        if(tmp <= num)
          v.push_back(num);
        else {
          v[0] = num;
          v.push_back(tmp);
        }
      }
      break;
      case 2:{
        if(v[0] + v[1] + num != 0)
          return false;
        else if(v[1] <= num)
          v.push_back(num);
        else if(v[0] <= num) {
          int temp = v[1];
          v[1] = num;
          v.push_back(temp);
        } else if(v[0] > num) {
          int t1 = v[0];
          int t2 = v[1];
          v[0] = num;
          v[1] = t1;
          v.push_back(t2);
        }
      }
      break;
      default:
        return false;
      break;
      }
      return true;
    }

    private:
      vector<vector<int>> m_vec;
};


TEST(threeSum, threeSum1) {
  GTEST_SKIP();
  Solution s1;
  vector<int> v1({1,2,-2,-1});
  auto ret = s1.threeSum(v1);

  for(int i = 0; i < ret.size(); i++) {
    printf("result is %d, %d, %d\n", ret[i][0], ret[i][1], ret[i][2]);
  }
}


